/* 
用户功能模块相关数据管理
*/
import {
  reqAutoLogin,
} from '../../api'
import {
  RECEIEVE_USER_INFO,
  RECEIEVE_TOKEN,
  RESET_USER_INFO,
  RESET_TOKEN,
} from '../mutations._type.js'
export default {
  state: {
    userInfo: {}, //用户信息
    token: localStorage.getItem('token_key') || '', // 当前用户登陆的标记},
  },
  mutations: {
    [RECEIEVE_USER_INFO](state, userInfo) {
      state.userInfo = userInfo
    },
    [RECEIEVE_TOKEN](state, token) {
      state.token = token
    },
    [RESET_USER_INFO](state) {
      state.userInfo = {}
    },
    [RESET_TOKEN](state) {
      state.token = ''
    },

  },
  actions: {
    // 保存用户登录信息
    saveUser({
      commit
    }, user) {
      const token = user.token
      localStorage.setItem('token_key', token)
      delete user.token // 删除user内部的token
      // 将token，user 提交到mutations中并保存到state中
      commit(RECEIEVE_USER_INFO, user)
      commit(RECEIEVE_TOKEN, token)
    },
    // 自动登录
    async autoLogin({
      commit
    }) {
      const result = await reqAutoLogin()

      if (result.code === 0) {
        const user = result.data
        commit(RECEIEVE_USER_INFO, user)
      }
    },
    // 退出登录
    logout({
      commit
    }) {
      localStorage.removeItem('token_key')
      commit(RESET_USER_INFO)
      commit(RESET_TOKEN)
    },
  },
  getters: {

  }
}